package com.kehutong.charge.service.impl;

import com.kehutong.charge.entity.ChargeTypeConfig;
import com.kehutong.charge.entity.MeterClassify;
import com.kehutong.charge.entity.MeterTypeConfig;
import com.kehutong.charge.service.MeterTypeService;
import com.kehutong.common.constant.RegexConstant;
import com.kehutong.common.errcode.Result;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.orm.Pool;
import org.coraframework.orm.annotation.Transaction;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.entity.FindPage;
import org.coraframework.util.Objects;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @program: kht
 * @description: MeterTypeServiceImpl
 * @author: joneron
 * @create: 2021/6/21
 **/
public class MeterTypeServiceImpl implements MeterTypeService {

    private static final Logger logger = LoggerFactory.getLogger(MeterTypeServiceImpl.class);
    /**初始化仪表类型,脚本初始化可能涉及表机构变更问题*/
    private static final Map<String,String[]> DEFAULT_METER_TYPE = new HashMap<>();
    static {
        DEFAULT_METER_TYPE.put("天然气", new String[]{"162683288095810006","m³"});
        DEFAULT_METER_TYPE.put("水表",  new String[]{"162677288357510000", "m³"});
        DEFAULT_METER_TYPE.put("电表",  new String[]{"162683286736010005","kwh"});
    }


    @Inject
    private JdbcSession jdbcSession;




    @Override
    public Page<MeterTypeConfig> findPage(JSONObject jsonObject) {
        this.initDefaultConfig();
        FindPage<MeterTypeConfig> find = jdbcSession.findPage(MeterTypeConfig.class)
                .eq("deleted", false)
                .like(jsonObject,"typeName")
                .order("sort", "desc")
                .order("createTime", "desc");
        find.page(jsonObject);
        Page<MeterTypeConfig>page = find.exe();

        List<MeterTypeConfig> list = page.getList();
        if(Objects.isEmpty(list)){
            return page;
        }

        Set<String> ids = list.stream().map(MeterTypeConfig::getId).collect(Collectors.toSet());
        List<MeterClassify> meterClassifyList = jdbcSession.findArray(MeterClassify.class)
                .eq("deleted",false)
                .in("meterTypeNo",ids)
                .exe();

        if(Objects.isEmpty(meterClassifyList)){
            return page;
        }

        list.stream().map(l-> { long count = meterClassifyList.stream().filter(m -> m.getMeterTypeNo().equals(l.getId())).count();
            l.setNumber((int) count);return l; }).collect(Collectors.toList());
        return page;
    }


    private void initDefaultConfig(){

        List<String> typeNameList = DEFAULT_METER_TYPE.keySet().stream().collect(Collectors.toList());
        List<MeterTypeConfig> dbDefaultList = jdbcSession.findArray(MeterTypeConfig.class)
                //.eq("deleted", false)
                .in("typeName", typeNameList)
                .eq("initData", true)
                .exe();
        if(!Objects.isEmpty(dbDefaultList)){
            return;
        }

        List<MeterTypeConfig> insertDefaultList = new ArrayList<>(DEFAULT_METER_TYPE.size());
        for (Map.Entry<String, String[]> entry : DEFAULT_METER_TYPE.entrySet()) {
            String key = entry.getKey();
            String[] value = entry.getValue();

            MeterTypeConfig typeConfig = Pool.newInstance(MeterTypeConfig.class);
            typeConfig.setId(value[0]);
            typeConfig.setUnit(value[1]);
            typeConfig.setPrecision("1");
            typeConfig.setCreateName("System");
            typeConfig.setTypeName(key);
            typeConfig.setStatus(true);
            typeConfig.setSort("999");
            typeConfig.setInitData(true);
            insertDefaultList.add(typeConfig);
        }
        jdbcSession.insert(insertDefaultList);
    }



    @Override
    public List<MeterTypeConfig> findList(JSONObject jsonObject) {
        return jdbcSession.findArray(MeterTypeConfig.class)
                .eq("deleted", false)
                .eq("status",true)
                .exe();
    }


    @Override
    public Object save(MeterTypeConfig meterTypeConfig) {

        String name = meterTypeConfig.getTypeName();
        List<MeterTypeConfig> listMt = jdbcSession.findArray(MeterTypeConfig.class)
                .eq("deleted", false)
                .eq("typeName",name).exe();

        if(listMt.size() > 0){
            return Result.error(2021, "类型名不能重复！");
        }

        //添加类型同时需要添加一条到配置表
        ChargeTypeConfig config = Pool.newInstance(ChargeTypeConfig.class);
        config.setStatus(true);
        config.setMeterTypeNo(meterTypeConfig.getId());
        config.setFeeTypeName(name);
        config.setCreateName(meterTypeConfig.getCreateName());
        config.setDepartmentName(meterTypeConfig.getDepartmentName());
        config.setDepartmentNo(meterTypeConfig.getDepartmentNo());
        config.setDepartmentNos(meterTypeConfig.getDepartmentNos());
        //需求变更
        //jdbcSession.insert(config);

        return jdbcSession.insert(meterTypeConfig);
    }


    @Override
    public Object update(MeterTypeConfig meterTypeConfig) {

        return jdbcSession.updateById(meterTypeConfig);
    }


    @Override
    public Object deleteById(String id) {
        MeterTypeConfig result = Pool.get(MeterTypeConfig.class, id);
        if (result != null) {
            result.setDeleted(true);
            jdbcSession.updateById(result);
        }
        return 1;
    }
}
